//
//  DownloadOperation.m
//  nsurlsession
//  Created by lk on 16/4/18.
//  Copyright © 2016年 lk. All rights reserved.
//

#import "LCDownloadManager.h"
#import "DownLoadOpration.h"
#define  ContentLocations [NSString stringWithFormat:@"%@/Documents/%@/%@",NSHomeDirectory(),_userflag,_storagePath]
@interface LCDownloadManager()<DownLoadOprationDelegate>
@property (nonatomic,strong)NSArray *doUrlArr;
@property (nonatomic,strong)NSArray *doNameArr;
@property (nonatomic,strong)DownLoadOpration *manger;
@property(nonatomic,strong)DownloadProgressBlock downloadProgressBlock;
@property(nonatomic,strong)DownloadSuccessBlock downloadSuccessBlock;
@property(nonatomic,strong)DownloadFailureBlock downloadFailureBlock;
@property(nonatomic,strong)PauseFinishBlock pausefinishBolock;
@property(nonatomic,strong)PauseFinishBlock restartfinishBlock;
@property(nonatomic,strong)DeletFinishBlock deletfinishBlock;
@property (nonatomic,strong)AllstartComplete allstartcomplete;
@property (nonatomic,strong)AllstopComplete allstopcompelete;
@property (nonatomic,strong)ExitSuccess exitsuccess;
@property (nonatomic,strong)PhoneLastCount lastCount;
@end
@implementation LCDownloadManager
static LCDownloadManager *LCdownloadManager = nil;
-(instancetype)initWithuserflag:(NSString *)userflag withStoragePath:(NSString *)storagePath
{
    if (self = [super init]) {
        _userflag = userflag;
        _storagePath = storagePath;
        _manger = [DownLoadOpration getInstance];
        _manger.userflag = userflag;
        _manger.storagePath = _storagePath;
        BOOL isDir  = NO;
        BOOL existed = NO;
        NSString *userlocal = [NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),_userflag];
        existed = [[NSFileManager defaultManager] fileExistsAtPath:userlocal isDirectory:&isDir];
        if ( !(isDir == YES && existed == YES) )
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:userlocal withIntermediateDirectories:YES attributes:nil error:nil];
        }
        existed = NO;
        isDir = NO;
        existed = [[NSFileManager defaultManager] fileExistsAtPath:ContentLocations isDirectory:&isDir];
        if ( !(isDir == YES && existed == YES) )
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:ContentLocations withIntermediateDirectories:YES attributes:nil error:nil];
        }
        NSMutableArray *urlArrs = [NSMutableArray arrayWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/%@/downArr.plist",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject],_userflag,_storagePath]];
        NSMutableArray *nameArrs = [NSMutableArray arrayWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/%@/storeArr.plist",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject],_userflag,_storagePath]];
        
        NSMutableArray *stopUrlArr = [NSMutableArray arrayWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/%@/stopurlArr.plist",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject],_userflag,_storagePath]];
        NSMutableArray *stopStorageArr = [NSMutableArray arrayWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/%@/stopstorageArr.plist",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject],_userflag,_storagePath]];
        
//        if (![_manger isNowDownForDownPath]) {
//            urlArrs = [NSMutableArray array];
//            [stopUrlArr addObjectsFromArray:urlArrs];
//            nameArrs = [NSMutableArray array];
//            [stopStorageArr addObjectsFromArray:nameArrs];
//            
//        }
        _manger.downPathMuArr = urlArrs;
        _manger.storagePathMuArr = nameArrs;
        _manger.stopDownpathArr = stopUrlArr;
        _manger.stopStorageArr = stopStorageArr;
        if (stopUrlArr == nil || stopUrlArr.count == 0) {
            _manger.stopDownpathArr = [NSMutableArray array];
        }
        if (stopUrlArr == nil || stopUrlArr.count == 0) {
            _manger.stopStorageArr = [NSMutableArray array];
        }
        if (urlArrs == nil || urlArrs.count == 0) {
            _manger.downPathMuArr = [NSMutableArray array];
        }
        _manger.delegate = self;
    }
    return self;
}
+(instancetype)getInstanceWithuserflag:(NSString *)userflag withStoragePath:(NSString *)storagePath
{
  
    @synchronized(self)
    {
        if(!LCdownloadManager)
        {
            LCdownloadManager = [[self alloc] initWithuserflag:userflag withStoragePath:storagePath];
        }
    }
    return LCdownloadManager;
    
}
-(void)downloadFileWith:(NSMutableArray *)urlArray withNameArr:(NSMutableArray*)nameArray progressbloack:(DownloadProgressBlock)progressBlock successBlock:(DownloadSuccessBlock)successBlock failureBlock:(DownloadFailureBlock)failureBlock
{
    if (progressBlock)
    {
        _manger.downloadProgressBlock = progressBlock;
    }
    if (successBlock) {
      _manger.downloadSuccessBlock = successBlock;
    }
    
    if (failureBlock) {
       _manger.downloadFailureBlock = failureBlock;
    }
    _doUrlArr = [NSArray array];
    _doNameArr = [NSArray array];
    _doUrlArr = [NSArray arrayWithArray:(NSMutableArray *)urlArray];
    _doNameArr = [NSArray arrayWithArray:(NSMutableArray *)nameArray];;
    [_manger pauseDownload];
}
-(void)mangerDidPause
{
    [self downloadWithUrlArr:_doUrlArr WithName:_doNameArr];
}
-(void)downloadWithUrlArr:(NSArray *)urlArr WithName:(NSArray *)nameArr
{
    _manger = [DownLoadOpration getInstance];
    NSArray *urlArrs = [NSArray arrayWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/%@/downArr.plist",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject],_userflag,_storagePath]];
    NSLog(@"%@",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject]);
    NSArray *nameArrs = [NSArray arrayWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/%@/storeArr.plist",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject],_userflag,_storagePath]];
    NSMutableArray *stopUrlArr = [NSMutableArray arrayWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/%@/stopurlArr.plist",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject],_userflag,_storagePath]];
    NSMutableArray *stopStorageArr = [NSMutableArray arrayWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/%@/stopstorageArr.plist",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject],_userflag,_storagePath]];
    NSMutableArray *downurl = [NSMutableArray arrayWithArray:urlArrs];
    NSMutableArray *downName = [NSMutableArray arrayWithArray:nameArrs];
    for (int i = 0; i < urlArr.count; i++) {
        NSString *filePth =[NSString stringWithFormat:@"%@/%@/%@/%@messagedic.plist",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject],_userflag,_storagePath,[nameArr[i] componentsSeparatedByString:@"."].firstObject];
        NSMutableDictionary *messageDic = [NSMutableDictionary dictionaryWithContentsOfFile:filePth];
        if ((messageDic == nil ||[messageDic allKeys] == 0 || [messageDic isEqual:[NSNull class]]) && ![downName containsObject:nameArr[i]] ) {
            [downurl addObject:urlArr[i]];
            [downName addObject:nameArr[i]];
        }
    }
    //判断是否重复下载
    if (downurl.count == 0) {
        
    }else
    {
        _manger.downPathMuArr = downurl;
        _manger.storagePathMuArr = downName;
        _manger.stopDownpathArr = stopUrlArr;
        _manger.stopStorageArr = stopStorageArr;
        if (stopUrlArr == nil || stopUrlArr.count == 0) {
            _manger.stopDownpathArr = [NSMutableArray array];
        }
        if (stopUrlArr == nil || stopUrlArr.count == 0) {
            _manger.stopStorageArr = [NSMutableArray array];
        }
        [_manger downloadFileWith:downurl];
    }
}
//暂停当前下载，开启下一个下载
-(void)pauseTaskWithLocalPath:(NSString *)localPath WithPauseFinishBolck:(PauseFinishBlock)pausefinishBolck
{
    if (pausefinishBolck) {
        _manger.pausefinishBolock = pausefinishBolck;
    }
    [_manger pauseTaskWithLocalPath:localPath];
}
//全部暂停，全部开始时，还是从原来的地方开始
-(void)pauseDownload
{
    [_manger pauseDownload];
}
//继续下载(对于下载的状态，在下载这边不维护，也就是说，下载时全部暂停下载的状态不会变化，主线程中根据是否点击全部暂停，来更改显示下载的状态，只要reloaddata一下就能改变过来)
-(void)resumeTask
{
    [_manger resumeTask];
}
-(NSDictionary *)getMessageWithCachePath:(NSString *)cachePath
{
    return [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/%@/%@messagedic.plist",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject],_userflag,_storagePath,[cachePath componentsSeparatedByString:@"."].firstObject]];
}
-(NSString *)getDownloadConditionWithCachePath:(NSString *)cachePath
{
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/%@/%@messagedic.plist",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject],_userflag,_storagePath,[cachePath componentsSeparatedByString:@"."].firstObject]];
    if (dic != nil || ![dic isKindOfClass:[NSNull class]]) {
        if ([[dic allKeys] containsObject:@"downcondition"]) {
            return dic[@"downcondition"];
        }
    }
    return  nil;
}
-(void)getdownloadWithProgressbloack:(DownloadProgressBlock)progressBlock successBlock:(DownloadSuccessBlock)successBlock failureBlock:(DownloadFailureBlock)failureBlock netBreakBlock:(NetBreakBlock)netBreakBlock
{
    if (progressBlock) {
       _manger.downloadProgressBlock = progressBlock;
    }
    if (successBlock) {
        _manger.downloadSuccessBlock = successBlock;
    }
    if (failureBlock) {
        _manger.downloadFailureBlock = failureBlock;
    }
    if (netBreakBlock) {
        _manger.netBeakBlock = netBreakBlock;
    }
    
}
-(NSString *)getContenDownloadPath
{
    if ([self isNowDownForDownPath]) {
        if (_manger.localName.length != 0) {
            return _manger.localName;
        }else
        {
            return @"";
        }
    }else
    {
        return @"";
    }
    
}
-(BOOL)isNowDownForDownPath
{
    return  [_manger isNowDownForDownPath];
}
-(void)deleteAll:(AllDeleteSuccess)alldeletsuccess
{
    if (alldeletsuccess) {
        _manger.alldeletsuccess = alldeletsuccess;
    }
    
    [_manger deleteAll];
}
-(BOOL)isNowDownForDownPath:(NSString *)localPath
{
    return  [_manger isNowDownForDownPath:localPath];
}
-(void)restartTaskWithLocalPath:(NSString *)localPath restartFinishBlock:(RestartFinishBlock)restartfinishBlock
{
    if (restartfinishBlock) {
       _manger.restartfinishBlock = restartfinishBlock;
    }
    [_manger restartTaskWithLocalPath:localPath];
}

-(void)allStopWithStopBlock:(AllstopComplete)allstopcomplete
{
    if (allstopcomplete) {
        _manger.allstopcompelete = allstopcomplete;
    }
    [_manger allStop];
}
-(void)allStartWithStartBlock:(AllstartComplete)allstartcomplete
{
    if (allstartcomplete) {
        _manger.allstartcomplete = allstartcomplete;
    }
    [_manger allStart];
}
-(void)deletDownloadTaskwith:(NSMutableArray *)urlArr WithNameArr:(NSMutableArray *)nameArr WithUserFlag:(NSString *)userflag withDeletfinshBlock:(DeletFinishBlock)deletfishBlock
{
    if (deletfishBlock) {
        _manger.deletfinishBlock = deletfishBlock;
    }
    [_manger deletDownloadTaskwith:urlArr WithNameArr:nameArr WithUserFlag:userflag];
}
-(void)exitTheprogramwithExitsuccessblock:(ExitSuccess)exitsuccess
{
    if (exitsuccess) {
       _manger.exitsuccess = exitsuccess;
    }
    [_manger exitTheprogram];
    LCdownloadManager = nil;
}
-(void)gainLastCount:(PhoneLastCount)lastCount
{
    if (lastCount) {
       _manger.lastCount = lastCount;
    }
    [_manger gainLastCount];
}
@end
